<template>
  <div>
    <Vue-editor
      v-model="content"
      placeholder="请输入文章内容"
      use-custom-image-handler
      @image-added="addImage"
      @text-change="$emit('send', content)"
    />
  </div>
</template>

<script>
  import { VueEditor } from 'vue2-editor'
  import { getImg } from '@/api/public'

  export default {
    components: { VueEditor },
    props: {
      oContent: {
        type: String,
        default: '',
      },
    },
    data() {
      return {
        content: '',
      }
    },
    watch: {
      oContent: {
        immediate: true,
        handler(newValue) {
          this.content = newValue
        },
      },
    },
    methods: {
      // 添加图片
      addImage(file, Editor, cursorLocation, resetUploader) {
        // 判断选择上传的图片文件类型，只允许上传jpg，png格式
        if (file.type == 'image/jpg' || file.type == 'image/png') {
          // 图片上传大小限制小于4MB
          if (file.size / 1024 / 1024 < 4) {
            let formData = new FormData()
            formData.append('file', file)

            getImg(formData).then((res) => {
              // 将获取的图片路径插入光标所在位置
              Editor.insertEmbed(cursorLocation, 'image', res.data)
              resetUploader()
            })
          } else {
            this.$message.error('图片大小不能大于4MB')
          }
        } else {
          this.$message.error('只支持jpg和png的图片文件上传')
        }
      },
    },
  }
</script>

<style scoped></style>
